<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 4/14/17
 * Time: 9:56 AM
 */

namespace api\modules\bank\controllers;

use common\components\bank\Icbc;
use common\components\tools\Model;
use common\components\tools\Tools;
use common\models\Bank;
use common\models\BankBackSendLog;
use common\models\BankGuaranteeCompanyBind;
use common\models\Car;
use common\models\CreditOrder;
use common\models\CreditOrderLog;
use common\models\Custom;
use common\models\DividedPaymentsOrder;
use common\models\DividedPaymentsOrderLog;
use common\models\GuaranteeCompanyDotSite;
use common\models\CarOrder;
use common\models\CarOrderLog;
use common\models\ManualPics;
use common\models\ManualPicsUploadQuene;
use common\models\MultiMediaOrder;
use common\models\MultiMediaOrderLog;
use common\models\MultiMediaUploadQuene;
use common\models\SpecialCard;
use common\models\SpecialCardAskLog;
use common\models\UsedCarEstimateOrder;
use common\models\UsedCarEstimateOrderLog;
use wodrow\yii\rest\ApiException;
use wodrow\yii\rest\Controller;
use workin\modules\others\models\FormMultiMediaUpload;
use yii\base\ErrorException;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use yii\log\FileTarget;

/**
 * Class BusinessController
 * @package api\modules\bank\controllers
 */
class BusinessController extends Controller
{
    /**
     * 添加客户
     * @desc 添加客户
     * @param string $guarantee_company_dot_site_sign_code 担保公司网点标识
     * @param int $guarantee_company_user_id 客户所在担保公司的用户id
     * @param string $bank_sign_code 提交银行标识
     * @param string $orderno 合作机构订单号<100
     */
    public function actionAddCustom($guarantee_company_dot_site_sign_code, $guarantee_company_user_id, $orderno, $master_name)
    {
        $guarantee_company_dot_site = GuaranteeCompanyDotSite::findOne(['sign_code' => $guarantee_company_dot_site_sign_code]);
        if (!$guarantee_company_dot_site) {
            throw new ErrorException('数据库中没有此担保公司网点', 1042);
        }
        if (!$guarantee_company_dot_site->guaranteeCompany) {
            throw new ErrorException('数据库中没有此担保公司', 1043);
        } else {
            $guarantee_company = $guarantee_company_dot_site->guaranteeCompany;
        }
        $custom = Custom::findOne(['guarantee_company_id' => $guarantee_company->id, 'guarantee_company_user_id' => $guarantee_company_user_id]);
        if ($custom && $custom->orderno != $orderno) {
            throw new ErrorException('客户订单号不匹配:req ' . $orderno . '; datatable ' . $custom->orderno, 1044);
        }
        if (!$custom) {
            $custom = new Custom();
            $custom->guarantee_company_user_id = $guarantee_company_user_id; //
            $custom->guarantee_company_id = $guarantee_company->id; //
            $custom->master_name = $master_name;
            $custom->orderno = $orderno;
            if (!$custom->save()) {
                throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($custom));
            }
        }
        return $custom->toArray();
    }

    /**
     * 提交征信
     * @desc 用户信用信息提交 $pics示例a:2:{i:0;a:2:{s:10:"image_type";s:3:"001";s:9:"image_url";s:4:"test";}i:1;a:2:{s:10:"image_type";s:3:"002";s:9:"image_url";s:5:"test1";}}
     * @param string $guarantee_company_dot_site_sign_code 担保公司网点标识
     * @param int $guarantee_company_user_id 客户所在担保公司的用户id
     * @param string $bank_sign_code 提交银行标识[已废弃]
     * @param string $bank_name 提交银行
     * @param string $orderno 合作机构订单号<100
     * @param string $master_name 主申请人名称<100
     * @param string $custom_name 客户名称<100
     * @param string $relation 关系:本人/配偶/反担保
     * @param string $idtype 证件类型<3
     * @param string $idno 证件编号<19
     * @param string $mobile 征信人手机号
     * @param string $pics 图片
     * @param int $add_water 是否加水印，默认进行7天重复请求判断
     * @param int $bairong_validate 是否验证百融大数据
     * @param int $dont_send_to_bank_api 是否不往银行发送数据
     * @return array $bankback 银行返回数据
     */
    public function actionSubmitCredit($guarantee_company_dot_site_sign_code, $guarantee_company_user_id, $bank_name, $orderno, $master_name, $custom_name, $relation, $idtype, $idno, $mobile = null, $pics, $add_water = 0, $bairong_validate = 0, $dont_send_to_bank_api = 0)
    {
//        Tools::log($orderno."    ".date("Y-m-d H:i:s"));
        $master_name = trim($master_name);
        $custom_name = trim($custom_name);
        $idno = trim($idno);
        $bank = Bank::getByName($bank_name);
        $guarantee_company_dot_site = GuaranteeCompanyDotSite::findOne(['sign_code' => $guarantee_company_dot_site_sign_code]);
        if (!$guarantee_company_dot_site) {
            throw new ErrorException('api数据库中没有此担保公司网点', 1042);
        }
        if (!$guarantee_company_dot_site->guaranteeCompany) {
            throw new ErrorException('api数据库中没有此担保公司', 1043);
        } else {
            $guarantee_company = $guarantee_company_dot_site->guaranteeCompany;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        try {
            $custom = Custom::findOne(['guarantee_company_id' => $guarantee_company->id, 'guarantee_company_user_id' => $guarantee_company_user_id]);
            if (!$custom) {
                $custom = new Custom();
                $custom->guarantee_company_user_id = $guarantee_company_user_id; //
                $custom->guarantee_company_id = $guarantee_company->id; //
                $custom->master_name = $master_name;
                $custom->orderno = $orderno;
                if (!$custom->save()) {
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($custom));
                }
            }
            $log = new CreditOrderLog();
            $log->serial_number = $cmpseq;
            $credit_order = CreditOrder::findOne(['custom_id' => $custom->id, 'relation' => $relation, 'idno' => $idno, 'idtype' => $idtype]);
            if (!$credit_order) {
                $credit_order = new CreditOrder();
                $credit_order->custom_id = $custom->id;
                $credit_order->relation = $relation;
                $credit_order->status = $credit_order::STATUS_DEFAULT;
                $credit_order->custname = $custom_name;
                $credit_order->idtype = $idtype;
                $credit_order->idno = $idno;
                $credit_order->bank_id = $bank->id;
                $credit_order->guarantee_company_dot_site_id = $guarantee_company_dot_site->id;
                $credit_order->mobile = $mobile;
                $credit_order->serialize_data = serialize(['pics' => $pics]);
                if (!$credit_order->save()) {
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($credit_order));
                }
            }
            $log->credit_order_id = $credit_order->id;
            $log->time = time();
            if (!$log->save()) {
                throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($log));
            }
            $credit_order = $log->creditOrder;
            $log->old_status = $credit_order->status;
            $credit_order->status = $credit_order::STATUS_HAS_SEND;
            if (!$credit_order->save()) {
                throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($credit_order));
            }
            $log->app_post_data = serialize($_REQUEST);
            $log->credit_order_data = serialize($credit_order->toArray());
            $log->new_status = $credit_order::STATUS_HAS_SEND;
            if ($bank->status != $bank::STATUS_API_USE) {
                $log->send_return_msg = 'success';
                $log->api_return_code = '00000';
                $log->api_return_msg = '不是api合作银行的认证!';
                $_r = [
                    'msg_code' => 2000,
                    'msg_msg' => '提交成功',
                    'msg_warning' => '不是api合作银行的认证!',
                ];
            } else {
                $bank_not7 = true;
                $_co = CreditOrder::find()->alias('co')
                    ->joinWith("creditOrderLogs as col")
                    ->where(['co.idno' => $idno])
                    ->andWhere(['col.api_return_code' => '00000'])
                    ->andWhere(['>', 'col.`time`', time() - 86400 * 7])
                    ->orderBy(['col.time' => SORT_DESC])
                    ->one();
                if ($_co) {
                    if ($_co->bank_id != $bank->id) {
                        $bank_not7 = true;
                    } else {
                        $bank_not7 = false;
                        $col = CreditOrderLog::find()->where(['credit_order_id' => $_co->id])->orderBy(['time' => SORT_DESC])->one();
                        $bbl = BankBackSendLog::find()->where(['for_serial_number' => $col->serial_number])->orderBy(['time' => SORT_DESC])->one();
                        if ($bbl) {
                            $r_d = unserialize($bbl->request_data);
                            $rdu = json_decode($r_d['reqparam']);
                            $x = ArrayHelper::toArray($rdu);
                            $result = $x['req']['result'];
                            if ($result == BankBackSendLog::BACK_CAN_RESEND) {
                                $bank_not7 = true;
                            } else {
                                $bank_not7 = false;
                            }
                        }
                    }
                }
                if (!$bank_not7) {
                    /*$_r = [
                        'msg_code' => 2001,
                        'msg_msg' => '已存在此征信订单',
                    ];*/
                    $add_water = 1;
                }
                if (!$dont_send_to_bank_api) {
                    $bank_company_bind = BankGuaranteeCompanyBind::findOne(['bank_id' => $bank->id, 'guarantee_company_id' => $guarantee_company->id]);
                    if (!$bank_company_bind) {
                        throw new ErrorException('api担保公司没有和银行完成绑定', 1044);
                    }
                    if ($custom->orderno != $orderno) {
                        throw new ErrorException('客户订单号不匹配:req ' . $orderno . '; datatable ' . $custom->orderno, 1044);
                    }
                    $pics = \common\components\tools\Bank::uploadIcbcPics0(unserialize($pics), $add_water, $guarantee_company->name);
                    $credit_order->serialize_data = serialize(['pics' => $pics]);
                    $cooperate = $bank_company_bind->cooperate;
                    $data = [
                        'pub' => [
                            'platno' => $bank_company_bind->apigw_appid,          //平台编号 6
                            'cmpseq' => $cmpseq, //合作机构交易流水号 Yyyymmddhh24miss+6位自生成序号 20
                            'zoneno' => $guarantee_company_dot_site->bank_zoneno,               //业务发生地  //todo 读取部门wg_code 4
                            'phybrno' => $bank->phybrno,            //业务受理网点 //todo 读取订单银行对应编号 8
                            'orderno' => $orderno,     // 合作机构订单号 <100
                            'assurerno' => $bank_company_bind->assurerno,        //担保单位编号	<20	工行业务部门提供参数表
                            'cmpdate' => date("Ymd"),             //合作机构日期	8	业务发生的日期
                            'cmptime' => date("His"),             //合作机构时间	6	业务发生的时间
                        ],
                        'req' => [
                            "customer" => [
                                "mastername" => $master_name,
                                "custname" => $custom_name,
                                "idtype" => $idtype,
                                "idno" => $idno,
                                "relation" => $relation,
                            ],
                            "pics" => $pics,
                        ],
                    ];
                    $cooperate->submitCredit($data);
                    $r = $cooperate->getReturn();
                    if ($r["send_return_msg"] == "success") {
                        if ($r["api_return_code"] == '22094') {
                            $bairong_validate = 0;
                            $_r = [
                                'msg_code' => 2002,
                                'msg_msg' => '灰名单',
                            ];
                        }elseif ($r["api_return_code"] == '22001'){
                            $_r = [
                                'msg_code' => 2005,
                                'msg_msg' => '已有查询',
                                'bank_return' => $r,
                            ];
                        }elseif ($r["api_return_code"] == '31003'){
                            $bairong_validate = 0;
                            $_r = [
                                'msg_code' => 2003,
                                'msg_msg' => '该客户经工行查询存在风险信息，拒绝!',
                                'bank_return' => $r,
                            ];
                        } else {
                            $_r = [
                                'msg_code' => 2000,
                                'msg_msg' => '提交成功',
                                'bank_return' => $r,
                            ];
                        }
                    } else {
                        $_r = [
                            'msg_code' => 2003,
                            'msg_msg' => '银行对接失败',
                        ];
                    }
                    $log->post_data = serialize($data);
                    $log->send_return_msg = $r["send_return_msg"];
                    $log->api_return_code = $r["api_return_code"];
                    $log->api_return_msg = $r["api_return_msg"];
                }else{
                    $_r = [
                        'msg_code' => 2111,
                        'msg_msg' => '不往银行发送数据',
                    ];
                }
            }
            if ($bairong_validate&&$mobile){
                $credit_order->baiRongValidate();
            }
            if (!$log->save()) {
                throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($log));
            }
            $transaction->commit();
            $_r['log'] = $log->toArray();
        } catch (ErrorException $e) {
            $transaction->rollBack();
            throw $e;
        }
        $_r['custom'] = $credit_order->custom->toArray();
        if ($bairong_validate){
            $br_result = $credit_order->getBairongResult();
            if (!$credit_order->big_data_validate_data && $bairong_validate == 1 && $mobile){
                $credit_order->big_data_validate_detail_shift_number = $br_result['swift_numbers']['detail_list'];
                $credit_order->big_data_validate_person_recognition_shift_number = $br_result['swift_numbers']['person_recognition'];
                $credit_order->big_data_validate_data = $br_result['optimize_show'];
            }
            $_r['bairong_result'] = $br_result;
        }
        $_r['order'] = $credit_order->toArray();
        return $_r;
    }

    /**
     * 查询征信
     * @desc 查询用户信用信息
     * @param string $orderno 合作机构订单号<100
     * @return array $credit_info 征信信息
     */
    public function actionCheckCredit($orderno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        $credit_orders = $custom->creditOrders;
        return $credit_orders;
    }

    /**
     * 申请分期付款
     * @desc post/get
     * @param string $orderno 合作机构订单号<100
     * @param string $serialize_data 序列化的请求信息
     * @return object $bankback 银行返回数据
     */
    public function actionAskForDividedPayments($orderno, $serialize_data = null)
    {
        $y = unserialize($serialize_data);
//        $y = $_REQUEST;
        $serialize_data = serialize([
            'customer' => [
                'Mobile' => $y['Mobile'],
                'Address' => $y['Address'],
                'Unit' => $y['Unit'],
            ],
            'car' => [
                'carType' => $y['carType'],
                'Price' => $y['Price'],
                'carNo1' => $y['carNo1'],
                'carRegNo' => $y['carRegNo'],
                'shorp4s' => $y['shorp4s'],
                'carNo2' => $y['carNo2'],
            ],
            'divi' => [
                'PaidAmt' => $y['PaidAmt'],
                'Amount' => $y['Amount'],
                'Term' => $y['Term'],
                'Interest' => $y['Interest'],
                'FeeMode' => $y['FeeMode'],
                'IsPawn' => $y['IsPawn'],
                'PawnGoods' => $y['PawnGoods'],
                'IsAssure' => $y['IsAssure'],
                'tiexiFlag' => $y['tiexiFlag'],
                'tiexiRate' => $y['tiexiRate'],
                'card' => $y['card'],
            ],
            'note' => $y['note'],
            'pics' => $y['pics'],
            'resubmit' => $y['resubmit'],
        ]);
        $data = unserialize($serialize_data);
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        $data['customer']['CustName'] = $credit_order->custom->master_name;
        $data['customer']['IdType'] = $credit_order->idtype;
        $data['customer']['IdNo'] = $credit_order->idno;
        $x = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'cmpseq' => $cmpseq,
                'zoneno' => $credit_order->guaranteeCompanyDotSite->bank_zoneno,
                'phybrno' => $credit_order->bankGuaranteeCompanyBind->bank->phybrno,
                'orderno' => $orderno,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
                'cmpdate' => date("Ymd"),
                'cmptime' => date("His"),
            ],
            'req' => $data,
        ];
        $response_content = $cooperate->askForDividedPayments($x);
        $t = \Yii::$app->db->beginTransaction();
        try {
            if ($cooperate->getReturn()["send_return_msg"] == "success") {
                $car = Car::findOne(['car_no1' => $data['car']['carNo1']]);
                if (!$car) {
                    $car = new Car();
                    $car->car_type = $data['car']['carType'];
                    $car->price = $data['car']['Price'];
                    $car->car_no1 = $data['car']['carNo1'];
                    $car->car_reg_no = $data['car']['carRegNo'];
                    $car->shorp4s = $data['car']['shorp4s'];
                    $car->car_no2 = $data['car']['carNo2'];
                    if (!$car->save()) {
                        throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($car));
                    }
                }
                $custom->mobile = $data['customer']['Mobile'];
                $custom->address = $data['customer']['Address'];
                $custom->unit = $data['customer']['Unit'];
                if (!$car->save()) {
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($car));
                }
                $divi = $custom->dividedPaymentsOrder;
                if (!$divi) {
                    $divi = new DividedPaymentsOrder();
                    $divi->custom_id = $custom->id;
                    $divi->car_id = $car->id;
                }
                $divi->serialize_data = $serialize_data;
                if (!$divi->save()) {
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($divi));
                }
                $log = new DividedPaymentsOrderLog();
                $log->serial_number = $cmpseq;
                $log->divided_payments_order_id = $divi->id;
                $log->time = time();
                $log->post_data = serialize($_REQUEST);
                $log->send_return_msg = $cooperate->getReturn()["send_return_msg"];
                $log->api_return_code = $cooperate->getReturn()["api_return_code"];
                $log->api_return_msg = $cooperate->getReturn()["api_return_msg"];
                $log->divided_payments_order_data = serialize($credit_order->toArray());
                $log->old_status = $divi::STATUS_DEFAULT;
                $log->new_status = $divi::STATUS_HAS_SEND;
                if (!$log->save()) {
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($log));
                }
                $t->commit();
            }
        } catch (ErrorException $e) {
            $t->rollBack();
            throw $e;
        }
        return $cooperate->getReturn();
    }

    /**
     * 查询申请进度 [通用业务]
     * @desc 查询申请进度
     * @param string $orderno 合作机构订单号<100
     * @return array $x ???
     */
    public function actionInquiryApplyRate($orderno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
//				'cmpseq' => date("YmdHis") . rand(100000, 999999),
                'zoneno' => $credit_order->guaranteeCompanyDotSite->bank_zoneno,
                'phybrno' => $credit_order->bankGuaranteeCompanyBind->bank->phybrno,
                'orderno' => $orderno,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
                'cmpdate' => date("Ymd"),
                'cmptime' => date("His"),
            ],
        ];
        $cooperate->inquiryApplyRate($data);
        $r = $cooperate->getReturn();
        $car_order = $custom->lastCarOrder;
        if ($car_order){
            $r['car_order'] = $car_order;
            $last_car_order_log = $car_order->lastCarOrderLog;
            $r['last_car_order_log'] = $car_order->lastCarOrderLog;
            $last_car_order_bank_back = $last_car_order_log->lastCarOrderBankBackLog;
            if ($last_car_order_bank_back){
                $r['last_car_order_bank_back'] = $last_car_order_bank_back->toArray();
            }
        }
        return $r;
    }

    /**
     * 专项卡上送
     * @desc 专项卡上送
     * @param string $orderno 合作机构订单号<100
     * @param string $serialize_data 请求数据
     * @param int $is_direct 是否不获取订单直接请求数据
     * @return object $bankback 银行返回数据
     */
    public function actionSubmitSpecialCard($orderno, $serialize_data, $is_direct = 0)
    {
        $data = unserialize($serialize_data);
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户", 100202);
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        $x = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'cmpseq' => $cmpseq,
                'zoneno' => $credit_order->guaranteeCompanyDotSite->bank_zoneno,
                'phybrno' => $credit_order->bankGuaranteeCompanyBind->bank->phybrno,
                'orderno' => $orderno,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
                'cmpdate' => date("Ymd"),
                'cmptime' => date("His"),
            ],
            'req' => [
                'loaninfo' => [
                    'loanamount' => $data['loanamount'],
                    'term' => $data['term'],
                    'feeratio' => $data['feeratio'],
                    'feeamount' => $data['feeamount'],
                    'carprice' => $data['carprice'],
                    'loanratio' => $data['loanratio']
                ],
//                'pics' => [
//                    [
//                        'picid' => $data[''],
//                        'picurl' => $data[''],
//                        'picnote' => $data['']
//                    ],
//                    [
//                        'picid' => $data[''],
//                        'picurl' => $data[''],
//                        'picnote' => $data['']
//                    ]
//                ],
//                'dscode' => $data[''],
//                'drawzon' => $data[''],
//                'drawbrno' => $data[''],
                'custsort' => $data['custsort'],
                'custcode' => $data['custcode'],
                'chnsname' => $data['chnsname'],
                'engname' => $data['engname'],
                'sex' => $data['sex'],
                'mrtlstat' => $data['mrtlstat'],
                'birthdate' => $data['birthdata'],
                'edulvl' => $data['edulvl'],
//                'homestat' => $data[''],
//                'hadrchoic' => $data[''],
                'hprovince' => $data['hprovince'],
                'hcity' => $data['hcity'],
                'hcounty' => $data['hcounty'],
                'haddress' => $data['haddrass'],
//                'haddrid' => $data[''],
                'homezip' => $data['homezip'],
                'hphonzono' => $data['hphonzono'],
                'hphoneno' => $data['hphoneno'],
//                'hphonext' => $data[''],
//                'mblchoic' => $data[''],
                'mvblno' => $data['mvblno'],
//                'mblid' => $data[''],
                'unitname' => $data['unitname'],
                'cophozono' => $data['cophozono'],
                'cophoneno' => $data['cophoneno'],
                'cophonext' => $data['cophonext'],
//                'cadrchoic' => $data[''],
                'cprovince' => $data['cprovince'],
                'ccity' => $data['ccity'],
                'ccounty' => $data['ccounty'],
                'caddress' => $data['caddress'],
//                'caddrid' => $data[''],
                'corpzip' => $data['corpzip'],
                'yearincome' => $data['yearincome'],
                'modelcode' => $data['modelcode'],
                'occptn' => $data['occptn'],
//                'comchoic' => $data[''],
//                'commprov' => $data[''],
//                'commcity' => $data[''],
//                'commcounty' => $data[''],
//                'commaddr' => $data[''],
//                'commaddrid' => $data[''],
//                'commazip' => $data[''],
                'reltname1' => $data['reltname1'],
                'reltsex1' => $data['reltsex1'],
                'reltship1' => $data['reltship1'],
                'reltmobl1' => $data['reltmobl1'],
//                'reltphzon1' => $data[''],
                'relaphone1' => $data['relaphone1'],
//                'reltphext1' => $data[''],
                'reltname2' => $data['reltname2'],
                'reltsex2' => $data['reltsex2'],
                'reltship2' => $data['reltship2'],
                'reltmobl2' => $data['reltmobl2'],
//                'rtcophzn2' => $data[''],
                'rtcophon2' => $data['relaphone2'],
//                'rtcophet2' => $data[''],
//                'cardkind' => $data[''],
//                'cardlogo' => $data[''],
//                'cardtype' => $data[''],
//                'cardmedm' => $data[''],
//                'allyno' => $data[''],
//                'almebno' => $data[''],
//                'fcurrtyp' => $data[''],
//                'expdate' => $data[''],
//                'feeflag' => $data[''],
//                'frfeeflag' => $data[''],
                'accgetm' => $data['accgetm'],
//                'accaddrf' => $data[''],
                'rmbcred' => $data['rmbcred'],
                'mamobile' => $data['mamobile'],
                'smsphone' => $data['smsphone'],
//                'qesno' => $data[''],
//                'answer' => $data[''],
//                'crdrflag' => $data[''],
                'authref' => $data['authref'],
                'statdate' => $data['statdate'],
                'indate' => $data['indate'],
                'joindate' => $data['joindate'],
//                'reltno' => $data[''],
//                'cardbin' => $data[''],
                'drawmode' => $data['drawmode'],
                'drawaddr' => $data['drawaddr'],
//                'saleno' => $data[''],
                'machgf' => $data['machgf'],
//                'machgmobile' => $data['machgmobile'],
                'emladdrf' => $data['emladdrf'],
//                'stmtemail' => $data[''],
//                'postxflg' => $data[''],
//                'slftxflg' => $data[''],
//                'atmtxflg' => $data[''],
//                'ddtrxtype' => $data[''],
//                'outacctype1' => $data[''],
//                'outcardno1' => $data[''],
//                'ddamttype1' => $data[''],
//                'outacctype2' => $data[''],
//                'outcardno2' => $data[''],
//                'ddamttype2' => $data[''],
//                'paydays' => $data[''],
//                'fftrxtype' => $data[''],
//                'ecshflag' => $data[''],
//                'appkind' => $data[''],
//                'creditcardno' => $data[''],
//                'prodname' => $data[''],
//                'featgype' => $data[''],
//                'featname' => $data[''],
//                'fakaorg' => $data[''],
            ],
        ];
        if (isset($data['pics'])) {
            $data['pics'] = \common\components\tools\Bank::uploadIcbcPicsCommon(\common\components\tools\Bank::DIR_SPECIAL_CARD, $data['pics']);
            $x['req']['pics'] = $data['pics'];
        }
        $cooperate->askForSpecialCard($x);
        $t = \Yii::$app->db->beginTransaction();
        try {
            $card = SpecialCard::findOne(['custom_id' => $custom->id]);
            $log = new SpecialCardAskLog();
            if (!$card) {
                $card = new SpecialCard();
                $card->custom_id = $custom->id;
                $card->status = $card::STATUS_DEFAULT;
                $card->serialize_data = $serialize_data;
            }
            $log->old_status = $card->status;
            $card->status = $card::STATUS_HAS_SEND;
            if (!$card->save()) {
                throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($card));
            }
            if ($cooperate->getReturn()["send_return_msg"] == "success") {
                $log = new SpecialCardAskLog();
                $log->serial_number = $cmpseq;
                $log->special_card_id = $card->id;
                $log->time = time();
                $log->app_post_data = serialize([
                    'orderno' => $orderno,
                    'serialize_data' => $serialize_data,
                    'is_direct' => $is_direct,
                ]);
                $log->post_data = serialize($data);
                $log->send_return_msg = $cooperate->getReturn()["send_return_msg"];
                $log->api_return_code = $cooperate->getReturn()["api_return_code"];
                $log->api_return_msg = $cooperate->getReturn()["api_return_msg"];
                $log->divided_payments_order_data = serialize($credit_order->toArray());
                $log->old_status = $card::STATUS_DEFAULT;
                $log->new_status = $card::STATUS_HAS_SEND;
            } else {
                $log = new SpecialCardAskLog();
                $log->serial_number = $cmpseq;
                $log->special_card_id = $card->id;
                $log->time = time();
                $log->post_data = serialize($_REQUEST);
                $log->send_return_msg = $cooperate->getReturn()["send_return_msg"];
                $log->divided_payments_order_data = serialize($credit_order->toArray());
                $log->old_status = $card::STATUS_DEFAULT;
                $log->new_status = $card::STATUS_HAS_SEND;
            }
            if (!$log->save()) {
                throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($log));
            }
            $t->commit();
            /*return [
                'success' => 1,
                'back' => $cooperate->getReturn(),
            ];*/
            return $cooperate->getReturn();
        } catch (ErrorException $e) {
            $t->rollBack();
            throw $e;
        }
    }

    /**
     * 文件清单信息下载
     * @param string $platno 平台编号(ysxc)
     * @param string $assurerno 担保单位编号(514)
     * @param int $filetype
     * @param string $filesrc 文件的存储地址
     * @param string $datadt 数据日期(YYYYMMDD)
     * @desc 文件清单信息下载
     */
    public function actionDownloadFileListInfo($platno, $assurerno, $filetype, $filesrc, $datadt)
    {
        /*$custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom->creditOrderSelf) {
            throw new ErrorException("本系统中在文件清单信息下载前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;*/
        $bankGuaranteeCompanyBind = BankGuaranteeCompanyBind::findOne(['apigw_appid' => $platno, 'assurerno' => $assurerno]);
        if (!$bankGuaranteeCompanyBind) {
            throw new ErrorException("没有找到银行和担保公司的绑定信息", 1054);
        }
        $cooperate = $bankGuaranteeCompanyBind->cooperate;
        $x = [
            'pub' => [
                'platno' => $bankGuaranteeCompanyBind->apigw_appid,
                'assurerno' => $bankGuaranteeCompanyBind->assurerno,
            ],
            'req' => [
                'filetype' => $filetype,
                'filesrc' => $filesrc,
                'datadt' => $datadt,
            ],
        ];
        $cooperate->downloadFileList($x);
        $r = $cooperate->getReturn();
        return $r;
    }

    /**
     * 风险准备金余额查询
     * @desc 用于查询合作机构在我行的风险准备金的余额,该交易由合作机构发起，发送客户征信查询请求。
     * @param string $orderno 合作机构订单号<100
     * @return object $bankback 银行返回数据
     */
    public function actionInquiryRiskProvisionBalance($orderno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
                'cmpseq' => $cmpseq,
            ],
        ];
        $cooperate->inquiryRiskProvisionBalance($data);
        $r = $cooperate->getReturn();
        return $r;
    }

    /**
     * 文件清单信息上送接口
     * @desc 上传逾期催缴文件 合作机构调用 文件格式参见附录3
     * @param string $orderno 合作机构订单号<100
     * @return object $bankback 银行返回数据
     */
    public function actionUploadFileListInfo($orderno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
            ],
            'req' => [
                'filetype' => '',
                'datadt' => '',
            ],
        ];
        $response_content = $cooperate->inquiryRiskProvisionBalance($data);
        $r = $cooperate->getReturn();
        return $r;
    }

    /**
     * 通用业务
     * @desc 通用业务(一手车，二手车)
     * @param int $busi_type 业务类别
     * @param string $orderno 合作机构订单号
     * @param string $cusName 客户名称
     * @param string $IdType 证件类型
     * @param string $IdNo 证件编号
     * @param string $serialize_data serialize
     * @return array
     * @throws ApiException
     * @throws ErrorException
     * @throws Exception
     * @throws \yii\base\Exception
     */
    public function actionCommonService($busi_type = 1, $orderno, $custName, $IdType, $IdNo, $serialize_data)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户", 100201);
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $_data = unserialize($serialize_data);
        $credit_order = $custom->lastCreditOrder;
        $resubmit = isset($_data['resubmit'])&&$_data['resubmit']!='' ? $_data['resubmit'] : $custom->checkResubmitForCarOrder($_data);
//        if ($orderno == '!bzqc000000046105'){
//            $resubmit = 1;
//        }
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        switch ($busi_type){
            case 1:
                $dirname = \common\components\tools\Bank::DIR_NEW_CAR;
                break;
            case 907:
                $dirname = \common\components\tools\Bank::DIR_USED_CAR;
                break;
            default:
                throw new ErrorException("busitype必填");
                break;
        }
        $zoneno = $credit_order->guaranteeCompanyDotSite->bank_zoneno;
        if (isset($_data['zonename'])&&$_data['zonename']){
            $_q = 0;
            if ($_data['zonename'] == '市辖区'||$_data['zonename'] == '县'){
                $_q = 1;
            }
            if (!in_array($_data['zonename'], Icbc::$zoneno_city_dict)){
                $_q = 1;
            }
            if ($_q){
                throw new ErrorException("词典中没有找到(".$_data['zonename']."),请到{$_SERVER['HTTP_HOST']}/frontend/help/icbc-zone-no-dict 手动输入zoneno");
            }else{
                $zoneno = array_search($_data['zonename'], Icbc::$zoneno_city_dict);
            }
        }
        if (isset($_data['zoneno'])&&$_data['zoneno']){
            $zoneno = $_data['zoneno'];
        }
        $pics = $_data['pics'];
        $auto_pics = [];
        $manual_pics = [];
        $media_pics = [];
        foreach ($pics as $k => $v) {
            if ($v['picid'] > 9000) {
                $manual_pics[] = $v;
            } else {
                if ($v['picid'] == 8888){
                    $media_pics[] = $v;
                }else{
                    $auto_pics[] = $v;
                }
            }
        }
        $auto_pics = \common\components\tools\Bank::UploadIcbcPicsCommon($dirname, $auto_pics);
        $manual_pics_upload_quene = new ManualPicsUploadQuene();
        $manual_pics_upload_quene->custom_id = $custom->id;
        $manual_pics_upload_quene->dirname = $dirname;
        $manual_pics_upload_quene->pics = json_encode($manual_pics);
        $manual_pics_upload_quene->created_at = time();
        $manual_pics_upload_quene->status = ManualPicsUploadQuene::STATUS_READY;
        if (!$manual_pics_upload_quene->save()){
            throw new ApiException(201809111600, "manual_pics_upload_quene保存失败:".Model::getModelError($manual_pics_upload_quene));
        }
        $media_upload_quene = MultiMediaUploadQuene::findOne(['custom_id' => $custom->id]);
        if(!$media_upload_quene){
            $media_upload_quene = new MultiMediaUploadQuene();
            $media_upload_quene->custom_id = $custom->id;
        }else{
            if ($media_upload_quene->status == 1){
                throw new ApiException(201903061138, "订单正在进行中，请稍后");
            }
        }
        $media_upload_quene->dirname = \common\components\tools\Bank::DIR_MULTI_MEDIA;
        $media_upload_quene->file_urls = json_encode($media_pics);
        $media_upload_quene->created_at = time();
        $media_upload_quene->status = MultiMediaUploadQuene::STATUS_READY;
        $media_upload_quene->idno = $IdNo;
        if (!$media_upload_quene->save()){
            throw new ApiException(201812171730, "media_upload_quene保存失败:".Model::getModelError($media_upload_quene));
        }
        /*$manual_pics = \common\components\tools\Bank::UploadIcbcPicsCommon($dirname, $manual_pics);
        ManualPics::deleteAll(['custom_id' => $custom->id]);
        foreach ($manual_pics as $k => $v){
            $_x = ManualPics::findOne(['custom_id' => $custom->id, 'picid' => $v['picid'], 'picurl' => $v['picurl']]);
            if (!$_x) {
                $_m_pic = new ManualPics();
                $_m_pic->custom_id = $custom->id;
                $_m_pic->picid = $v['picid'];
                $_m_pic->picurl = $v['picurl'];
                $_m_pic->created_at = time();
                $_m_pic->picnote = isset($v['picnote']) ? $v['picnote'] : null;
                $_m_pic->save();
            }
        }*/
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'cmpseq' => $cmpseq,
                'zoneno' => $zoneno,
                'phybrno' => $credit_order->bankGuaranteeCompanyBind->bank->phybrno,
                'orderno' => $orderno,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
                'cmpdate' => date("Ymd"),
                'cmptime' => date("His"),
                'busitype' => $busi_type, // 907:二手车,1:新车
            ],
            'req' => [
                'customer' => [
                    'CustName' => $custName, // 客户名称
                    'IdType' => $IdType, // 证件类型
                    'IdNo' => $IdNo, // 证件编号
                    'Mobile' => $_data['Mobile'], // 联系电话
                    'Address' => $_data['Address'], // 家庭住址
                    'Unit' => $_data['Unit'], // 单位名称
                ],
                'Note' => $_data['Note'], // 申请备注
                'busi' => [
                    'car' => [
                        'carType' => $_data['carType'], // 车辆型号
                        'Price' => $_data['Price'], // 车辆价格
                        'carNo1' => $_data['carNo1'], // 车架号
                        'carRegNo' => $_data['carRegNo'], // 登记证书编号
//                        'shorp4s' => '', // 4S店名称
                        'carNo2' => $_data['carNo2'], // 车牌号
//                        'AssessPrice' => $_data['AssessPrice'], // 车辆评估价格
//                        'AssessOrg' => $_data['AssessOrg'], // 评估机构
//                        'UsedYears' => $_data['UsedYears'], // 使用年限（月）
                    ],
                    'divi' => [
                        'PaidAmt' => $_data['PaidAmt'], // 首付金额
                        'Amount' => $_data['Amount'], // 分期金额
                        'Term' => $_data['Term'], // 分期期数
                        'Interest' => $_data['Interest'], // 分期手续费率 8.5%
                        'FeeMode' => $_data['FeeMode'], // 手续费收取方式
                        'IsPawn' => $_data['IsPawn'], // 是否抵押
                        'PawnGoods' => $_data['PawnGoods'], // 抵押物 车架号+车辆型号
                        'IsAssure' => $_data['IsAssure'], // 是否担保
//                        'tiexiFlag' => $_data['tiexiFlag'], // 是否贴息
//                        'tiexiRate' => $_data['tiexiRate'], // 贴息费率
                        'card' => $_data['card'], // 信用卡
                    ],
                ],
                'pics' => $auto_pics,
                'resubmit' => $resubmit, // 继续申请标志
            ],
        ];
        switch ($busi_type){
            case 1:
                $data['req']['busi']['car']['shorp4s'] = '';
                $data['req']['busi']['divi']['tiexiFlag'] = $_data['tiexiFlag']; // 是否贴息
                $data['req']['busi']['divi']['tiexiRate'] = $_data['tiexiRate']; // 贴息费率
                break;
            case 907:
                $data['req']['busi']['car']['AssessPrice'] = $_data['AssessPrice']; // 车辆评估价格
                $data['req']['busi']['car']['AssessOrg'] = $_data['AssessOrg']; // 评估机构
                $data['req']['busi']['car']['UsedYears'] = $_data['UsedYears']; // 使用年限（月）
                break;
            default:
                break;
        }
        $cooperate->askForGeneralService($data);
        $r = $cooperate->getReturn();
        if ($r["send_return_msg"] == "success") {
            $trans = \Yii::$app->db->beginTransaction();
            try {
                if ($x = CarOrder::findOne(['id_no' => $IdNo])) {
                    $car_order = $x;
                } else {
                    $car_order = new CarOrder();
                }
                $car_order->custom_id = $custom->id;
                $car_order->cust_name = $custName;
                $car_order->id_no = $IdNo;
                $car_order->serialize_data = serialize($data);
                $car_order->car_type = $car_order::TYPE_USED;
                $car_order->save(false);
                $log = new CarOrderLog();
                $log->car_order_id = $car_order->id;
                $log->created_at = time();
                $log->serial_number = $cmpseq;
                $log->send_return_msg = $r["send_return_msg"];
                $log->api_return_code = $r["api_return_code"];
                $log->api_return_msg = $r["api_return_msg"];
                $log->app_post_data = serialize([
                    'orderno' => $orderno,
                    'serialize_data' => $serialize_data,
                ]);
                $log->post_data = serialize($data);
                $log->response_data = serialize($r);
                $log->save(false);
                $trans->commit();
            } catch (Exception $e) {
                $trans->rollBack();
                throw $e;
            }
        }
        return $r;
    }

    /**
     * 租金分期业务申请
     * @desc 租金分期业务申请
     * @param string $orderno 合作机构订单号<100
     * @return object $bankback 银行返回数据
     */
    public function actionAskForRentDiviService($orderno, $pics)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $pics = unserialize($pics);
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'cmpseq' => $cmpseq,
                'zoneno' => $credit_order->guaranteeCompanyDotSite->bank_zoneno,
                'phybrno' => $credit_order->bankGuaranteeCompanyBind->bank->phybrno,
                'orderno' => $orderno,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
                'cmpdate' => date("Ymd"),
                'cmptime' => date("His"),
                'busitype' => 909,
            ],
        ];
    }

    /**
     * 获取上次专项卡请求数据
     * @desc get/post
     * @param string $orderno
     * @return array
     * @throws ErrorException
     */
    public function actionGetSpecialCardLastPostData($orderno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        if ($custom->specialCard) {
            if ($custom->specialCard->lastSpecialCardAskLog) {
                $post_data = unserialize($custom->specialCard->lastSpecialCardAskLog->app_post_data);
                $r = [
                    'post_data' => $post_data,
                ];
                return $r;
            }
        }
        return [];
    }

    /**
     * 获取上次车辆订单请求数据
     * @desc get/post
     * @param string $orderno
     * @return array
     * @throws ErrorException
     */
    public function actionGetCarOrderLastPostData($orderno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        if ($custom->lastCarOrder) {
            if ($custom->lastCarOrder->lastCarOrderLog) {
                $post_data = unserialize($custom->lastCarOrder->lastCarOrderLog->app_post_data);
                $r = [
                    'post_data' => $post_data,
                ];
                return $r;
            }
        }
        return [];
    }

    /**
     * 查询专项卡开卡进度
     * @desc 该交易由合作机构发起。
     * @param $orderno
     * @return object $bankback 银行返回数据
     */
    public function actionInquerySpecialCardSchedule($orderno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户", 1002034);
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'zoneno' => $credit_order->guaranteeCompanyDotSite->bank_zoneno,
                'phybrno' => $credit_order->bankGuaranteeCompanyBind->bank->phybrno,
                'orderno' => $orderno,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
            ],
        ];
        $cooperate->inquirySpecialCardSchedule($data);
        /*$ft = new FileTarget();
        $ft->logFile = \Yii::$app->getRuntimePath() . "/logs/inquery_special_card.log";
        $ft->messages[] = [$data, 1, 'request', time()];
        $ft->messages[] = [$cooperate->getReturn(), 1, 'respone', time()];
        $ft->export();
//        return $response_content;*/
        return $cooperate->getReturn();
    }

    /**
     * 远程面签接口-信息查询
     * @desc 查询申请远程面签客户的相关信息
     * @param string $orderno 合作机构订单号<100
     * @return object $bankback 银行返回数据
     */
    public function actionInquiryRemoteInterviewInfo($orderno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'cmpseq' => $cmpseq,
                'assurerno' => $credit_order->bankGuaranteeCompanyBind->assurerno,
                'cmpdate' => date("Ymd"),
                'cmptime' => date("His"),
            ],
            'req' => [
                'customer' => [
                    'custname' => '',
                    'idtype' => '',
                    'idno' => '',
                ],
            ],
        ];
    }

    /**
     * 通用业务多媒体资料补充接口
     * @desc 上传需要补充的业务资料
     * @param string $orderno 合作机构订单号<100
     * @param serialize $pics 多媒体资料
     * @param string $pics 多媒体资料
     * @return object $bankback 银行返回数据
     */
    public function actionSupplyGeneralServiceMultimedia($orderno, $pics, $idno)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            throw new ErrorException("没有找到该订单客户");
        }
        /*if (!$custom->creditOrderSelf) {
            throw new ErrorException("本系统中在申请通用业务多媒体资料补充接口有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order_self = $custom->creditOrderSelf;*/
        /*$credit_order = $custom->creditOrderSelf;
        if (!$credit_order){
            $credit_order = $custom->lastCreditOrder;
        }*/
        $credit_order = CreditOrder::find()->where(['custom_id' => $custom->id, 'idno' => $idno])->one();
        if (!$credit_order){
            throw new ErrorException("未找到身份证号码为{$idno}的征信", 1053);
        }
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $pics = unserialize($pics);
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'cmpseq' => $cmpseq,
                'guestPlatno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid, // 平台编号<6 此处为需要补充资料对应的平台编号
//                'zoneno' => $credit_order->guaranteeCompanyDotSite->bank_zoneno,
                'orderno' => $orderno,
                'idno' => $credit_order->idno,
                'cmpdate' => date("Ymd"),
                'cmptime' => date("His"),
            ],
            'req' => [
//                'customer' => [
//                    'custname' => '',
//                    'idtype' => '',
//                    'idno' => '',
//                ],
                'pics' => $pics,
            ],
        ];
        $cooperate->supplyGeneralServiceMultimedia($data);
        $r = $cooperate->getReturn();
        if ($r["send_return_msg"] == "success") {
            $trans = \Yii::$app->db->beginTransaction();
            try {
                if ($x = MultiMediaOrder::findOne(['id_no' => $credit_order->idno])) {
                    $multi_media_order = $x;
                } else {
                    $multi_media_order = new MultiMediaOrder();
                }
                $multi_media_order->custom_id = $custom->id;
                $multi_media_order->id_no = $credit_order->idno;
                $multi_media_order->serialize_data = serialize($data);
                $multi_media_order->save(false);
                $log = new MultiMediaOrderLog();
                $log->multi_media_order_id = $multi_media_order->id;
                $log->created_at = time();
                $log->serial_number = $cmpseq;
                $log->send_return_msg = $r["send_return_msg"];
                $log->api_return_code = $r["api_return_code"];
                $log->api_return_msg = $r["api_return_msg"];
                $log->app_post_data = serialize([
                    'orderno' => $orderno,
                ]);
                $log->post_data = serialize($data);
                $log->response_data = serialize($r);
                $log->save(false);
                $trans->commit();
            } catch (Exception $e) {
                $trans->rollBack();
                throw $e;
            }
        }
        return $r;
    }


    /**
     * 二手车评估
     * @desc get/post
     * @param string $orderno 合作机构订单号<100
     * @param string $serialize_data 请求数据
     * @return object $bankback 银行返回数据
     * @throws
     */
    public function actionUsedCarEstimate($orderno, $serialize_data)
    {
        $custom = Custom::findOne(['orderno' => $orderno]);
        if (!$custom) {
            $custom = Custom::findOne(['guarantee_company_id' => 1, 'guarantee_company_user_id' => $orderno]);
            if (!$custom)throw new ErrorException("没有找到该订单客户");
        }
        if (!$custom->creditOrderSelf) {
//            throw new ErrorException("本系统中在申请专项卡前必须有本人征信，然而没有找到征信信息", 1053);
        }
        $credit_order = $custom->lastCreditOrder;
        $cooperate = $credit_order->bankGuaranteeCompanyBind->cooperate;
        $cmpseq = date("YmdHis") . rand(100000, 999999);
        $_s_data = unserialize($serialize_data);
        $data = [
            'pub' => [
                'platno' => $credit_order->bankGuaranteeCompanyBind->apigw_appid,
                'cmpseq' => $cmpseq,
//                'guestPlatno' => '', // 平台编号<6 此处为需要补充资料对应的平台编号
//                'zoneno' => $credit_order->guaranteeCompanyDotSite->bank_zoneno,
                'orderno' => $custom->orderno,
                'cmpdate' => date("Ymd"),
                'cmptime' => date("His"),
            ],
            'req' => [
                'customer' => [
//                    'custname' => '',
                    'idtype' => '000',
                    'idno' => $_s_data['idno'],
                ],
                'car' => [
                    'carType' => $_s_data['carType'], // 车辆型号 <= 100
                    'Price' => $_s_data['Price'], // 拟分期金额（元） <= 20
                    'carNo1' => $_s_data['carNo1'], // 车架号 <= 100
                    'carZone' => array_search($_s_data['carZone'],Icbc::$zoneno_city_dict), // 所在城市 <= 100
                    'carMile' => $_s_data['carMile'], // 行驶里程 <= 20
                    'carDate' => $_s_data['carDate'], // 首次上牌日期 == 8
                    'AssessPrice' => $_s_data['AssessPrice'], // 线下评估价格（元） <= 20
                    //'EvaluateOrg' => $_s_data['EvaluateOrg'], // 评估机构 <= 20 默认送0：加我科技评估机构1
                    'decorateLevel' => $_s_data['decorateLevel'], // 高配/一般/低配 == 1 非必填，可为空 0:低配 1:一般 2:高配
                ],
            ],
        ];
        $response_content = $cooperate->usedCarEstimate($data);
        $r = $cooperate->getReturn();
        $trans = \Yii::$app->db->beginTransaction();
        try {
            if ($cooperate->getReturn()["send_return_msg"] == "success") {
                $_order = new UsedCarEstimateOrder();
                $_order->custom_id = $custom->id;
                $_order->serialize_data = serialize($data);
                $_order->save(false);
                $log = new UsedCarEstimateOrderLog();
                $log->used_car_estimate_order_id = $_order->id;
                $log->created_at = time();
                $log->serial_number = $cmpseq;
                $log->send_return_msg = $r["send_return_msg"];
                $log->api_return_code = $r["api_return_code"];
                $log->api_return_msg = $r["api_return_msg"];
                $log->app_post_data = serialize([
                    'orderno' => $orderno,
                    'serialize_data' => $serialize_data,
                ]);
                $log->post_data = serialize($data);
                $log->response_data = serialize($r);
                $log->save(false);
                $trans->commit();
            }
        } catch (Exception $e) {
            $trans->rollBack();
            throw $e;
        }
        return $r;
    }
    /******
     ***** 二手车评估
     ***** @desc get/post 使用ICBC支行接口
     ***** @param string $guarantee_company_dot_site_sign_code 担保公司网点标识
     ***** @param string $bank_name 提交银行
     ***** @throws
     *****/
    /*public function actionUsedCarEstimate($guarantee_company_dot_site_sign_code, $bank_name)
    {
        $bank = Bank::getByName($bank_name);
        $guarantee_company_dot_site = GuaranteeCompanyDotSite::findOne(['sign_code' => $guarantee_company_dot_site_sign_code]);
        if (!$guarantee_company_dot_site) {
            throw new ApiException(201812141228, 'api数据库中没有此担保公司网点');
        }
        if (!$guarantee_company_dot_site->guaranteeCompany) {
            throw new ApiException(201812141229, 'api数据库中没有此担保公司');
        } else {
            $guarantee_company = $guarantee_company_dot_site->guaranteeCompany;
        }
        $bank_company_bind = BankGuaranteeCompanyBind::findOne(['bank_id' => $bank->id, 'guarantee_company_id' => $guarantee_company->id]);
        if (!$bank_company_bind) {
            throw new ApiException(201812141227, 'api担保公司没有和银行完成绑定');
        }
        $cooperate = $bank_company_bind->cooperate;
    }*/

    /**
     * 多媒体文件上传
     * @desc get/post
     * @param string $idno 身份证
     * @param string $urls 用,隔开
     * @throws
     */
    public function actionUploadMediaFile($idno, $urls)
    {
        $sql = <<<SQL
SELECT orderno FROM credit_order_log
LEFT JOIN credit_order ON credit_order.id = credit_order_id
LEFT JOIN bank ON bank_id = bank.id
LEFT JOIN custom ON custom_id = custom.id
WHERE idno='{$idno}' -- 作为参数
AND bank.`name` = '中国工商银行股份有限公司杭州延中支行' -- 作为参数
AND api_return_code = '00000'
ORDER BY field(relation, '本人', '配偶', '反担保', '担保人'), credit_order_log.time desc
LIMIT 0,1
SQL;
        $data = \Yii::$app->db->createCommand($sql)->queryOne();
        $custom = Custom::findOne(['orderno' => $data['orderno']]);
        if (!$custom) {
            throw new Exception("没有找到该订单客户 ".date("Y-m-d H:i:s"));
        }
        $model = new FormMultiMediaUpload();
        $model->custom_id = $custom->id;
        $model->custom_name = $custom->master_name;
        $model->idno = $idno;
        $model->urls = $urls;
        if ($model->validate()){
            $model->addQuene(",");
            return ['msg' => "加入上传队列成功"];
        }else{
            throw new ApiException(201902191736, "加入失败");
        }
    }
}